//前提：启动mongod服务
// 1. 安装mongoose
// 2. 导入mongoose
const mongoose = require('mongoose');

// http://localhost:80/
// 3. 连接数据库 - 参数：数据库地址：协议://本机地址:端口号/数据库名称
mongoose.connect('mongodb://localhost:27017/CD0417')
// 4. 创建连接回调 connection.on("open",callback)
mongoose.connection.on('open',()=>{
    console.log("数据库连接成功");

    // 5. 创建文档解构 new mongoose.Schema()
    let booksSchema = new mongoose.Schema({
        name:String,
        author:String,
        price:Number,
        score:Number
    })
    // 6. 创建模型对象 mongoose.model()
    let booksModel = mongoose.model('books',booksSchema);
    // 7. 插入文档 model.create({},callback)

    booksModel.insertMany([{
        name:"红楼梦",
        author:"曹雪芹",
        price:9.9,
        score:9.2
    }])

    // 8. 关闭链接【选做】
})
    
// 9. 创建失败回调 connection.on("error",callback)
mongoose.connection.on('error',()=>{
    console.log("数据库连接失败");
})